from django.forms import widgets
from django.forms.utils import flatatt
from django.utils.safestring import mark_safe


class ColorRadioSelect(widgets.RadioSelect):
    def render(self, name, value, attrs=None, renderer=None):
        if value is None:
            value = ''
        final_attrs = self.build_attrs(attrs, {'name': name})
        output = ['<div class="color-picker">']
        options = self.choices
        
        for i, (option_value, option_label) in enumerate(options):
            # 检查是否选中
            selected = str(option_value) == str(value)
            
            # 获取颜色值
            # 从COLOR_CHOICES中获取十六进制颜色值
            color_value = option_label
            # 确保颜色值以#开头
            if not color_value.startswith('#'):
                color_value = '#' + color_value
            
            # 创建单选按钮
            input_id = f"{name}_{i}"
            input_attrs = {
                'type': 'radio',
                'name': name,
                'id': input_id,
                'value': option_value,
                'class': 'color-radio-input',
            }
            
            if selected:
                input_attrs['checked'] = 'checked'
            
            # 构建单选按钮HTML
            input_html = f'<input {flatatt(input_attrs)} />'
            
            # 构建标签HTML（包含颜色预览）
            label_html = f'<label for="{input_id}" class="color-label">'
            label_html += f'<span class="color-preview" style="background-color: {color_value};"></span>'
            label_html += '</label>'
            
            # 添加到输出
            output.append(f'<div class="color-option">{input_html} {label_html}</div>')
        
        output.append('</div>')
        return mark_safe(''.join(output))

    class Media:
        css = {
            'all': ('css/color_picker.css',)
        }